// search 相关的仓库

import { Article } from '@/types/data'
import { RootAction } from '@/types/store'
import { getHistory } from '@/utils/history'

type InitType = {
  suggestion: string[]
  history: string[]
  results: Article[]
}

const initValue: InitType = {
  suggestion: [],
  history: getHistory(), // 搜索记录存在仓库, 存在本地
  results: [], //搜索结果 文章数组
}

export default function searchReducer(
  state: InitType = initValue,
  action: RootAction
) {
  if (action.type === 'search/set_suggestion') {
    return {
      ...state,
      suggestion: action.payload,
    }
  }

  if (action.type === 'search/set_history') {
    return {
      ...state,
      history: action.payload,
    }
  }

  if (action.type === 'search/clear_history') {
    return {
      ...state,
      history: [],
    }
  }

  if (action.type === 'search/set_results') {
    return {
      ...state,
      results: [...state.results, ...action.payload],
    }
  }

    if (action.type === 'search/clear_results') {
      return {
        ...state,
        results: [],
      }
    }

  return state
}
